package com.smartrm.trade.application.executor;

import com.google.common.collect.Lists;
import com.smartrm.globalinfrcore.cmd.AbstractCommandContext;
import com.smartrm.globalinfrcore.exception.DomainException;
import com.smartrm.trade.domain.SlotVendingMachineDO;
import com.smartrm.trade.domain.remote.CommodityInfo;
import com.smartrm.trade.domain.valueobject.PaymentQrCodeVOJ;
import com.smartrm.trade.domain.valueobject.PlatformType;
import com.smartrm.trade.domain.valueobject.StockedCommodityVOJ;
import com.smartrm.trade.infrasturcture.TradeError;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

/*
 * @program: common-starters
 * @description: 选择商品命令：使用智能命令，将实现和命令放在一起
 * @author: houhong
 * @create: 2023-01-11 22:21
 */
@Component
public class SelectCommodityCmd extends AbstractTradeCmd<PaymentQrCodeVOJ> {

    private static final Logger logger = LoggerFactory.getLogger(SelectCommodityCmd.class);


    /*
     * 依赖于领域层组织业务
     */
    @Override
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public PaymentQrCodeVOJ execute(AbstractCommandContext context) throws Exception {

        VendingCommandContext vendingCommandContext = (VendingCommandContext) context;

        Long machineId = vendingCommandContext.getMachineId();
        String commodityId = vendingCommandContext.getCommodityId();
        PlatformType platformType = vendingCommandContext.getPlatformType();
        //通过仓储获取到货道售卖机聚合根
        SlotVendingMachineDO slotVendingMachineDO = vendingMachineRepository.getSlotVendingMachineById(machineId);
        //做校验
        if (slotVendingMachineDO == null) {
            logger.warn("vending machine not found:{}", machineId);
            throw new DomainException(TradeError.VendingMachineNotFound);
        }
        //// TODO: 2023/1/11 使用领域层完成需求
        CommodityInfo commodityInfo = tradeCommodityService.getCommodityDetail(commodityId);

        StockedCommodityVOJ commodity = new StockedCommodityVOJ(
                commodityInfo.getCommodityId(),
                commodityInfo.getCommodityName(),
                commodityInfo.getImageUrl(),
                commodityInfo.getPrice(),
                1
        );
        PaymentQrCodeVOJ qrCodeVOJ = slotVendingMachineDO.selectCommodity(Lists.newArrayList(commodity),
                tradeDeviceService, tradePayService, platformType);
        return qrCodeVOJ;
    }
}